package com.gdut.simple.view.activity.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.gdut.file.FileActivity;
import com.gdut.simple.R;
import com.gdut.simple.basic.BasicApplication;
import com.gdut.simple.common.DataCleanManager;
import com.gdut.simple.common.ProgressUtils;
import com.gdut.simple.event.PrefEvent;
import com.gdut.simple.event.RxBus;
import com.gdut.simple.event.UpdateThemeEvent;
import com.gdut.simple.event.UserEvent;
import com.gdut.simple.view.basic.AbsBasicActivity;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import rx.functions.Action1;

public class PreferenceActivity extends AbsBasicActivity {

    @BindView(R.id.id_toolbar)
    Toolbar toolbar;
    @BindView(R.id.id_default_download_path)
    TextView mDownloadPathText;
    @BindView(R.id.id_cache_size_text)
    TextView mCacheSizeText;
    @BindView(R.id.id_change_night_mode)
    Switch mNightModeSwitch;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_preference);
        ButterKnife.bind(this);
        initToolbar();
        initSwitch();
    }

    private void initToolbar() {
        toolbar.setTitle(R.string.title_pref);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initSwitch() {
        BasicApplication application = (BasicApplication) getApplication();
        mNightModeSwitch.setChecked(application.isNightMode());
        mNightModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    changeToNightMode();
                } else {
                    changeToDayMode();
                }
                recreateOnResume();
                RxBus.getDefault().post(new UpdateThemeEvent());
            }
        });
    }

    @Override
    protected void loadData() {
        bindData();
        mSubscription = RxBus.getDefault().toObservable(PrefEvent.class).subscribe(new Action1<PrefEvent>() {
            @Override
            public void call(PrefEvent prefEvent) {
                bindData();
            }
        });
    }

    private void bindData() {
        try {
            mCacheSizeText.setText(DataCleanManager.getTotalCacheSize(BasicApplication.getApplication()));
            mDownloadPathText.setText(getDownloadPath());
            ProgressUtils.hide();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getDownloadPath() {
        SharedPreferences sp = getPreferences(MODE_PRIVATE);
        String path = sp.getString("download_path", "");
        if (path.isEmpty()) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getApplicationName();
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("download_path", path);
            editor.apply();
        }
        return path;
    }

    private String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            applicationInfo = null;
        }
        return (String) packageManager.getApplicationLabel(applicationInfo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (data != null) {
                String path = data.getStringExtra("data");
                SharedPreferences sp = getPreferences(MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("download_path", path);
                editor.apply();
                RxBus.getDefault().post(new PrefEvent());
            }
        }
    }

    @OnClick(R.id.id_download_path_layout)
    void setmDownloadPath() {
        FileActivity.startActivityForResult(PreferenceActivity.this, mDownloadPathText.getText().toString(), 100);
    }

    @OnClick(R.id.id_clear_cache_layout)
    void clearCache() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("确认清除所有缓存？")
                .setPositiveButton("清除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ProgressUtils.show(PreferenceActivity.this, "清除中...");
                        DataCleanManager.clearAllCache(BasicApplication.getApplication());
                        RxBus.getDefault().post(new PrefEvent());
                    }
                })
                .setNegativeButton("取消", null);
        builder.show();
    }

    @OnClick(R.id.id_user_logout)
    void logout() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("退出当前账号");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                BmobUser.logOut();
                UserEvent event = new UserEvent(false);
                RxBus.getDefault().post(event);
                finish();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }
}
